package com.zlm.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zlm.common.CustomException;
import com.zlm.common.Result;
import com.zlm.dto.DishDto;
import com.zlm.dto.SetmealDto;
import com.zlm.entity.*;
import com.zlm.service.CategoryService;
import com.zlm.service.SetmealDishService;
import com.zlm.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


import static com.zlm.utils.RedisConstants.SETMEAL_CACHE_KEY;

/**
 * 套餐管理
 */

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    //这个就是查询我们我们的套餐的名字关联表用的
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Resource
    private CacheManager cacheManager;

    /**
     * 这个就是我们保存套餐的方法
     * 注意这个保存设计到了两张表所以我们使用的是dto新创建的类 这样就能包含全部信息
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public Result<String> save(@RequestBody SetmealDto setmealDto) {
        log.info(setmealDto.toString());

        return setmealService.saveWithDish(setmealDto);

    }


    /**
     * 套餐分页查询 但是我们要有我们的套餐的名字才行
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize, String name) {
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        // SetmealDto才是我们真正的字段
        Page<SetmealDto> setmealDtoPage = new Page<>(page, pageSize);

        // 条件构造器
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(name != null, Setmeal::getName, name);
        // 排序条件(更新时间来降序排列)
        lambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);

        // 调用方法来查询
        setmealService.page(pageInfo, lambdaQueryWrapper);

        // 忽略我们的数据 因为我们需要我们的名字
        BeanUtil.copyProperties(pageInfo, setmealDtoPage, "records");
        List<Setmeal> setmealRecords = pageInfo.getRecords();
        List<SetmealDto> setmealDtos = null;
        setmealDtos = setmealRecords.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();

            // 基本类型
            BeanUtil.copyProperties(item, setmealDto);
            // 得到分类的id
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            // 得到我们套餐的名字
            String categoryName = category.getName();
            setmealDto.setCategoryName(categoryName);
            return setmealDto;

        }).collect(Collectors.toList());

        // 再将我们弄好的完成数据放入进去
        setmealDtoPage.setRecords(setmealDtos);

        return Result.success(setmealDtoPage);
    }


    /**
     * 回显数据的
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<SetmealDto> getByIdWithFlavor(@PathVariable("id") Long id) {
        Setmeal setmeal = setmealService.getById(id);
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmeal.getId());
        List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);
        // 菜品回显
        setmealDto.setSetmealDishes(setmealDishes);
        return Result.success(setmealDto);
    }

    /**
     * 修改套餐数据
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public Result<String> update(@RequestBody SetmealDto setmealDto) {
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDto, setmeal);
        boolean b = setmealService.updateById(setmeal);
        // 将原来的菜品全部移除
        for (SetmealDish item : setmealDishes) {
            setmealDishService.removeById(item.getId());
            item.setSetmealId(setmealDto.getId());
        }
        // 再重新保存
        setmealDishService.saveBatch(setmealDishes);

        return setmealService.updateWithDish(setmealDto);
    }


    /**
     * 对菜品进行删除 并且我们的口味也要删除
     *
     * @param ids
     * @return
     */
    @Transactional
    @DeleteMapping// 注意
    @CacheEvict(value = "setmealCache", allEntries = true)
    public Result<String> deleteWithDish(String[] ids) {


        // 将里面全部需要删除取出来
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Setmeal::getId, ids);
        lambdaQueryWrapper.eq(Setmeal::getStatus, 1);
        int count = (int) setmealService.count(lambdaQueryWrapper);
        if (count > 0) {
            throw new CustomException("套餐正在售卖，不能删除");
        }

        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.in(Setmeal::getId, ids);
        setmealService.remove(lambdaQueryWrapper1);

        // 删除口味的
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(setmealDishLambdaQueryWrapper);

        return Result.success("删除成功");

    }

    /**
     * 根据id修改我们售卖的状态
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache", allEntries = true)
    public Result<String> updateStatus(@PathVariable("status") int status, Long[] ids) {
        // 现根据我们的id查询到实体类
        List<Setmeal> setmeals = setmealService.listByIds(Arrays.asList(ids));
        for (Setmeal setmeal : setmeals) {
            setmeal.setStatus(status);
            LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Setmeal::getId, setmeal.getId());
            setmealService.update(setmeal, lambdaQueryWrapper);
        }

        /*for (Long id : ids) {

            Dish dish = dishService.getById(id);
            dish.setStatus(status);

            LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Dish::getId, id);
            dishService.update(dish, lambdaQueryWrapper);

        }*/


        return Result.success("修改成功");
    }

    /**
     * 消费者前台页面显示套餐相关的内容
     * 这里不能用RequestBody注解接收参数，是因为传来的参数不是完整的对象并且不是Json，只是对象的一部分
     * 用k-v形式进行传输，所以不能用RequestBody接收
     *
     * @param setmeal
     * @return
     */
    // 注意这个返回的status永远都是1
    @GetMapping("/list")  // 在消费者端 展示套餐信息
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")
    public Result<List<Setmeal>> list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        Long categoryId = setmeal.getCategoryId();
        Integer status = setmeal.getStatus();
        //种类不为空才查
        queryWrapper.eq(categoryId != null, Setmeal::getCategoryId, categoryId);

        //在售状态才查
        queryWrapper.eq(Setmeal::getStatus, 1);

        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> setmeals = setmealService.list(queryWrapper);

        return Result.success(setmeals);
    }


}
